import React, { useState } from 'react';
import { useDropzone } from 'react-dropzone';
import axios from 'axios';

const FileUpload = () => {
    const [uploading, setUploading] = useState(false);
    const [error, setError] = useState('');

    const onDrop = async (acceptedFiles) => {
        setUploading(true);
        setError('');
        const file = acceptedFiles[0];
        const formData = new FormData();
        formData.append('excelFile', file);

        try {
            await axios.post('http://localhost:3000/kai/upload', formData, {
                headers: {
                    'Content-Type': 'multipart/form-data'
                }
            });
            console.log('文件上传成功');
        } catch (err) {
            setError('文件上传失败');
            console.error(err);
        } finally {
            setUploading(false);
        }
    };

    const { getRootProps, getInputProps } = useDropzone({ onDrop });

    return (
        <div {...getRootProps()} style={{ display: 'inline - block', border: '1px dashed #ccc', padding: '10px 20px',fontSize:'0.3rem',cursor: 'pointer' }}>
            <input {...getInputProps()} />
            {uploading? (
                <span>上传中...</span>
            ) : error? (
                <span style={{ color: 'red' }}>{error}</span>
            ) : (
                <span>上传 Excel 文件</span>
            )}
        </div>
    );
};

export default FileUpload;